package com.concurrence;

import com.Example.Model.Transfer.Transfer;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.client.RepChainJksClient;
import com.protos.Peer;
import org.apache.commons.codec.binary.Hex;

import java.util.Random;

public class Node4Thread implements Runnable {

    private RepChainJksClient adminClient = new RepChainJksClient("localhost:8081","jks/921000005k36123789.node4.jks", "123", "921000005k36123789.node4");

    private Peer.ChaincodeId contractAssetsId = Peer.ChaincodeId.newBuilder().setChaincodeName("ContractAssetsTPL").setVersion(1).build();

    // 管理员证书ID
    private Peer.CertId adminCertId = Peer.CertId.newBuilder().setCreditCode("921000005k36123789").setCertName("node4").build();

    private Random random = new Random();

    private int node4;

    private int node5;

    private int[] amount = new int[]{0,0,0,0,0,0};

    @Override
    public void run() {
        try {
            for (int i = 1; i <= 1000; i++) {
//                int amount = random.nextInt(100);
                int amount = 50;
                Transfer.TransferBuilder builder = Transfer.builder();
                builder.from("921000005k36123789");
                builder.to("921000006e0012v696");
                builder.amount(amount);
                node4 -= amount;
                node5 += amount;
                String str_trans = JSON.toJSONString(builder.build());
                //这个是给转账交易示范用的，此ID需要与repchain合约部署的一致
                Peer.Transaction transfer = adminClient.createTransactionForInvoke(adminCertId, contractAssetsId, "transfer", str_trans);
                String transferstr = Hex.encodeHexString(transfer.toByteArray());
                // 将交易数据post过去
                JSONObject transferResult = adminClient.postTranByString(JSONObject.toJSONString(transferstr));
                System.out.println(Thread.currentThread().getName() + ": " + transferResult);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public int getNode4() {
        return node4;
    }

    public void setNode4(int node4) {
        this.node4 = node4;
    }

    public int getNode5() {
        return node5;
    }

    public void setNode5(int node5) {
        this.node5 = node5;
    }
}
